<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>WebSocket 流式响应测试</title>
    <style>
        #messages {
            border: 1px solid #ccc;
            padding: 10px;
            height: 300px;
            overflow-y: auto;
            /* 防止文本换行 */
            white-space: nowrap;
            /* 内容超出时显示水平滚动条 */
            overflow-x: auto;
        }

        #messages p {
            /* 允许内联显示 */
            display: inline;
        }
    </style>
</head>
<body>
<input id="messageInput" placeholder="输入消息" type="text">
<button onclick="sendMessage()">发送</button>
<div id="messages"></div>

<script>
    let socket;
    const messagesDiv = document.getElementById('messages');
    const messageInput = document.getElementById('messageInput');
    // const wsUrl = 'wss://api.yx.ryoi.cn/resource/websocket';
    const wsUrl = 'ws://192.168.1.18:9090/resource/websocket';

    function initWebSocket() {
        socket = new WebSocket(wsUrl);

        socket.onopen = function () {
            console.log('WebSocket 连接已建立');
            showMessage('系统提示：WebSocket 连接已建立');
        };

        socket.onmessage = function (event) {
            try {
                // 解析接收到的 JSON 数据
                const data = JSON.parse(event.data);
                // 提取 choices 数组中第一个元素的 delta 对象的 content 字段
                const content = data.choices && data.choices[0] && data.choices[0].delta && data.choices[0].delta.content;
                if (content) {
                    const message = document.createElement('p');
                    // 直接显示原始内容
                    message.textContent = content;
                    messagesDiv.appendChild(message);
                }
            } catch (error) {
                console.error('解析消息时出错:', error);
                showMessage('系统提示：解析消息时出错，请检查');
            }
        };

        socket.onclose = function () {
            console.log('WebSocket 连接已关闭');
            showMessage('系统提示：WebSocket 连接已关闭，尝试重新连接...');
            // 重连机制
            setTimeout(() => {
                reconnect();
            }, 3000);
        };

        socket.onerror = function (error) {
            console.error('WebSocket 发生错误:', error);
            showMessage('系统提示：WebSocket 发生错误，请检查连接');
        };
    }

    function sendMessage() {
        const message = messageInput.value;
        if (message) {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.send(JSON.stringify({
                    content: message,
                    model: "deepseek/deepseek-r1",
                    messages: []
                }));
                messageInput.value = '';
            } else if (socket && socket.readyState === WebSocket.CONNECTING) {
                showMessage('系统提示：连接正在建立中，请稍候...');
            } else {
                showMessage('系统提示：连接未建立，尝试重新连接...');
                reconnect();
            }
        }
    }

    function reconnect() {
        if (socket && (socket.readyState === WebSocket.CLOSING || socket.readyState === WebSocket.CLOSED)) {
            initWebSocket();
        }
    }

    function showMessage(text) {
        const message = document.createElement('p');
        message.textContent = text;
        messagesDiv.appendChild(message);
    }

    // 初始化 WebSocket 连接
    initWebSocket();
</script>
</body>
</html>
